﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PlatWL.Data;
using System.Data;
using PlatWL.Services.Tools;
using System.Transactions;
using System.IO;
using Senparc.Weixin.MP.AdvancedAPIs.OAuth;

namespace PlatWL.Services.ServicesWeb
{
    public class AuthManage
    {

        /// <summary>
        /// 发送验证码
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="Client"></param>
        /// <param name="telephone"></param>
        public void SendSms(ref Msg_Result msg, int Client, string telephone,string flag)
        {
            if (flag == "reg") //注册判断手机号是否已经注册
            {
                var chU = new pt_user_accountb().GetEntity(p => p.Telephone == telephone);
                if (chU != null)
                {
                    msg.error = "手机号已经注册";
                    return;
                }
            }
            string smscode = Common.RndNum(6);
            Common.SendSMS(telephone, "SMS_12971767", "{\"code\":\"" + smscode + "\",\"product\":\"飓速网\"}");

            CacheHelp.Put(Common.Md5(telephone), smscode + "|" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
        }

        /// <summary>
        /// 获取随机码
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="Client"></param>
        /// <param name="telephone"></param>
        /// <param name="flag"></param>
        public Stream RandomCode(ref Msg_Result msg, int Client, string telephone, string flag)
        {
            //if (flag == "reg") //注册判断手机号是否已经注册
            //{
            //    var chU = new PT_User_AccountB().GetEntity(p => p.Telephone == telephone);
            //    if (chU != null)
            //    {
            //        msg.error = "手机号已经注册";
            //        return null;
            //    }
            //}
            string smscode = Common.RndNum2(4);
            byte[] img = Common.CreateValidateGraphic(smscode);
            Stream streamImg = new MemoryStream(img);
            CacheHelp.Put(Common.Md5(telephone), smscode + "|" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

            return streamImg;
        }

        #region 登陆注册模块
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="Client"></param>
        /// <param name="user_account"></param>
        public void Login(ref Msg_Result msg, int Client, string telephone, string password)
        {
            password = Common.Md5(password);
            var usr = new pt_user_accountb().GetEntityFirst(p => p.Telephone == telephone && p.Password == password);
            if (usr != null)
            {
                msg.result = GetToken(usr.ID);
            }
            else
            {
                msg.error = "手机号或密码错误";
            }
        }

        /// <summary>
        /// 根据微信code，判定是否绑定，如果绑定立即登录
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="Client"></param>
        /// <param name="code"></param>
        public void WXCode(ref Msg_Result msg, int Client, string code)
        {
            var wxUser = WXHelp.GetUserInfoByCode(code);
            if (wxUser != null)
            {
                var txUser = new pt_user_accountb().GetEntityFirst(p => p.OpenID == wxUser.openid);
                if (txUser != null)
                {
                    msg.error = "1";//直接登录
                    msg.result = GetToken(txUser.ID);
                }
                else
                {
                    //缓存微信抓取的用户信息
                    CacheHelp.Put(code, wxUser);
                }
            }
                

        }

        /// <summary>
        /// 注册
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="Client"></param>
        /// <param name="user_account"></param>
        public void Reg(ref Msg_Result msg, int Client, string telephone, string password, string smscode,string refid,string rdm,string code)
        {
            //1.先判断验证码是否正确
            var smsCodeV = Tools.CacheHelp.Get(Common.Md5(rdm));
            if (smsCodeV == null || smsCodeV.ToString().Split('|')[0].ToUpper() != smscode.ToUpper() || DateTime.Parse(smsCodeV.ToString().Split('|')[1]).AddMinutes(30) < DateTime.Now)
            {
                msg.error = "验证码错误或已过期";
                return;
            }

            OAuthUserInfo wxUser = new OAuthUserInfo();
            //绑定手机号
            if (!string.IsNullOrEmpty(code))
            {
                wxUser = CacheHelp.Get<OAuthUserInfo>(code);
                if (string.IsNullOrEmpty(wxUser.openid))
                {
                    msg.error = "获取code错误";
                    return;
                }
            }

            //2.判断手机号格式

            //3.注册
            var usr = new pt_user_accountb().GetEntityFirst(p => p.Telephone == telephone);
            if (usr != null)
            {
                if (!string.IsNullOrEmpty(code)) //微信绑定已存在账号
                {
                    //1.判断密码是否正确
                    if (usr.Password != Tools.Common.Md5(password))
                    {
                        msg.error = "绑定已有账号，密码不正确";
                        return;
                    }
                    else
                    {
                        usr.OpenID = wxUser.openid;
                        usr.NickName = wxUser.nickname;
                        if (wxUser.sex == 1)
                        {
                            usr.Sex = "男";
                        }
                        if (wxUser.sex == 2)
                        {
                            usr.Sex = "女";
                        }
                        usr.Province = wxUser.province;
                        usr.City = wxUser.city;
                        usr.County = wxUser.country;
                        usr.UserImg = wxUser.headimgurl;

                        new pt_user_accountb().Update(usr);
                        msg.result = GetToken(usr.ID);
                    }
                }
                else
                {
                    msg.error = "手机号已存在";

                }
            }
            else
            {
                //增加事务机制
                using (TransactionScope ts = new TransactionScope())
                {

                    password = Tools.Common.Md5(password);
                    usr = (new pt_user_account()
                    {
                        Telephone = telephone,
                        Password = password,
                        Point = 0,
                        Balance = 0,
                        UserType = 1,
                        Lev = 0,
                        UpID = 0,
                        Status = 0,
                        Deleted = 0,
                        CRTime = DateTime.Now
                    });

                    int rID = 0;
                    if (refid != "" && Int32.TryParse(refid, out rID))
                    {
                        usr.RefID = rID;
                    }

                    if (!string.IsNullOrEmpty(wxUser.openid))
                    {
                        usr.OpenID = wxUser.openid;
                        usr.NickName = wxUser.nickname;
                        if (wxUser.sex == 1)
                        {
                            usr.Sex = "男";
                        }
                        if (wxUser.sex == 2)
                        {
                            usr.Sex = "女";
                        }
                        usr.Province = wxUser.province;
                        usr.City = wxUser.city;
                        usr.County = wxUser.country;
                        usr.UserImg = wxUser.headimgurl;
                    }
                       

                    new pt_user_accountb().Insert(usr);


                    msg.result = GetToken(usr.ID);


                    ts.Complete();
                }

            }
        }


        //产生token
        public string GetToken(int UserID)
        {
            string token = "";
            var tk = new pt_auth_tokenb().GetEntityFirst(p => p.UserID == UserID);
            if (tk == null)
            {
                token = Tools.Common.GuID();
                new pt_auth_tokenb().Insert(new pt_auth_token()
                {
                    Client = -1,
                    UserID = UserID,
                    Token = token,
                    TokenTime = DateTime.Now,
                    ExpireTime = DateTime.Now.AddDays(30),
                    ISAdmin = 0
                });
            }
            else
            {
                token = tk.Token;
            }
            return token;
        }

        #endregion


        public void GetTui(ref Msg_Result msg, int Client, int UserID)
        {
            var usr = new pt_user_accountb().GetEntity(p => p.ID == UserID);
            if (usr != null)
            {
                msg.result = new { NickName = string.IsNullOrEmpty(usr.TrueName) ? usr.NickName : usr.TrueName, UserImg = usr.UserImg };
            }

        }
    }
}
